<template>
  <div>
    <!-- action="http://47.97.79.225:9020/fileMgr/v1/oss/upload/aliyun" -->
    <el-upload
      action=""
      :class="hiddenUp ? 'img-hide' : ''"
      :http-request="requestHttp"
      :multiple="limit != 1"
      list-type="picture-card"
      :on-success="successHandle"
      :on-remove="handleRemove"
      :on-exceed="outInputFile"
      :file-list="updataArr"
      :limit="limit"
      :before-upload="beforeUploadHandle"
      :show-file-list="showFileList"
    >
      <!-- <i class="el-icon-plus"></i> -->
      <img
        v-if="value && value[0] && !showFileList"
        :src="value[0]"
        class="avatar"
      />
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      <!-- <i class="el-icon-plus avatar-uploader-icon"></i> -->
    </el-upload>
  </div>
</template>

<script>
import axios from 'axios'
import Vue from 'vue'
export default {
  props: {
    value: {
      type: Array,
      default: []
    },
    // showFileList false  只允许上传1张图片，多次上传覆盖前一张,还需limit设置为3
    showFileList: {
      type: Boolean,
      default: true
    },
    limit: {
      type: Number,
      default: 10
    },
    dialogVisible: {
      type: Boolean,
      default: false
    },
    clearVisible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      visible: false,
      url: '',
      num: 0,
      successNum: 0,
      updataArr: [], // 回显值
      urlUidImg: [], // 上传值
      hiddenUp: false,
      removeType: false
    }
  },
  watch: {
    dialogVisible(n, o) {
      if (!n) {
        this.updataArr = []
      }
    },

    value(n, o) {
      // this.updataArr=[]
      if (n && n.length > 0) {
        n.forEach(item => {
          let obj = new Object()
          obj.url = item
          this.updataArr.push(obj)
        })
      }

      this.length()
    }
  },
  mounted() {
    console.log(this.limit)
    if (this.value) {
      this.value.forEach(item => {
        let obj = new Object()
        obj.url = item
        this.updataArr.push(obj)
      })
      this.length()
    }
  },
  methods: {
    handleRemove(file, fileList) {
      let removeArr = []
      if (fileList.length > 0) {
        if (this.urlUidImg.length > 0) {
          this.urlUidImg.forEach(element => {
            if (file.uid != element.uid) {
              if (element.url) {
                removeArr.push(element.url)
              } else {
                removeArr.push(element)
              }
            }
          })
        } else {
          fileList.forEach(e => {
            if (e.url) {
              removeArr.push(e.url)
            } else {
              removeArr.push(e)
            }
          })
        }

        this.updataArr = fileList
      } else {
        removeArr = []
        this.updataArr = []
      }
      this.removeType = true
      this.length()
      this.$emit('updataImg', removeArr)
    },

    // 上传之前
    beforeUploadHandle(file) {
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG && !isPNG) {
        this.$message.error('上传图片只能是 JPG /png格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return (isJPG || isPNG) && isLt2M
      this.num++
    },
    // 随机生成文件名
    random_string(len) {
      len = len || 32
      var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz123456789'
      var maxPos = chars.length
      var pwd = ''
      for (let i = 0; i < len; i++) {
        pwd += chars.charAt(Math.floor(Math.random() * maxPos))
      }
      return pwd
    },
    requestHttp(file) {
      let formData = new FormData()
      formData.append('file', file.file)
      let config = {
        headers: {
          token: Vue.cookie.get('token'),
          'Content-Type': 'multipart/form-data'
        }
      }
      this.uploadLoding = true
      axios
        .post(
          `${this.$config.SERVER_URL}/admin/sys/oss/upload`,
          formData,
          config
        )
        .then(obj => {
          this.uploadLoding = false
          if (obj.status == 200) {
            let fileUrl = obj.data.data.url
            let editorArr = []
            this.urlUidImg = this.updataArr
            if (!this.showFileList) {
              this.urlUidImg = []
            }
            this.urlUidImg.push({
              url: fileUrl,
              uid: file.file.uid
            })
            this.urlUidImg.forEach(element => {
              if (element.url) {
                editorArr.push(element.url)
              } else {
                editorArr.push(element)
              }
            })
            this.$emit('updataImg', editorArr)
            this.length()
          }
        })
    },
    outInputFile(files, fileList) {
      if (fileList.length >= this.limit && this.showFileList) {
        this.hiddenUp = true
        this.$message.warning('最多只能上传' + this.limit + '张图片')
        return false
      } else {
        this.hiddenUp = false
      }
    },
    length() {
      if (this.updataArr.length >= this.limit) {
        this.hiddenUp = true
      } else {
        this.hiddenUp = false
      }
    },
    // 上传成功
    successHandle(response, file, fileList) {
      console.log(file, fileList)
      this.successNum++
    }
  }
}
</script>
<style lang="scss" scoped>
// .img-hide .el-upload--picture-card {
// 		display: none;
// 	}
//   .el-upload-list--picture-card .el-upload-list__item-thumbnail{
//     height: auto !important;
//   }
//   .el-upload-list--picture-card .el-upload-list__item{
//     line-height: 148px !important;
//   }
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>
